<?php

namespace app\model\v1\setup;

use app\model\order\StoreOrder;
use app\model\user\User;
use app\model\v1\gift\GiftCard;
use app\model\v1\gift\GiftCardCate;
use app\model\v1\gift\GiftCardUser;
use app\model\v1\gift\RecruitLanguage;
use app\services\order\StoreOrderCreateServices;
use app\services\user\UserAddressServices;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Db;
use think\Model;


class SetupLimits extends Model
{

    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
    //    'create_time','update_time','delete_time'
    ];

    protected $table = 'eb_setup_limits';




    /**
     * 菜单管理列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getSetUpLimitsList($params = [])
    {
        $data = self::field("*")
            ->where(function ($query) use ($params){
                $query->where("is_del", 0);
                if(!empty($params['tag_id'])) $query->where("tag_id", $params['tag_id']); //根据分类标签搜索
            })
            //->order(['id'=>'desc'])
            //->page($params["page"], $params['limit'])
            ->select()->toArray();

        return $data;
    }


    public static function add_limits($param = [])
    {
        $add = [
            "pid"               => $param["pid"] ?? '',
            "name"              => $param["name"] ?? '',
            "url"               => $param["url"] ?? '',
            "sort"              => $param["sort"] ?? '',
            "url_name"          => $param["url_name"] ?? '',
            "ctime"             => date("Y-m-d H:i:s"),
        ];
        return self::insert($add);
    }





    /**
     * 礼品卡详情
     * @param $id
     * @return GiftCard|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftCardDetail($id)
    {
        $detail = self::field("*")
            ->with([
                "catetag" => function ($query) {
                    $query->field("id,cate_tag_name");
                }
            ])
            ->where("id", $id)
            ->whereNull("delete_time")
            ->find();
        if(!empty($detail["content"])) $detail['content'] = htmlspecialchars_decode($detail['content']);

        return $detail;
    }


    /**
     * 创建礼品卡订单
     * @param int $uid
     * @param array $param
     * @return string|\think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createGiftOrder(int $uid, array $param)
    {
        //$order_find = StoreOrder::where(["type" => GiftCard::ORDER_TYPE, "activity_id"=>$param["gift_card_id"],"uid"=>$uid])->find();
        //if(!empty($order_find)) Throw new Exception('不能重复下单');
        $num = $param['num'] ?? 1;
        $stock_num = SetupLimits::where("id", $param['gift_card_id'])->value('stock_num') ?? 0;
        if($stock_num < $num) Throw new Exception('礼品卡库存不足！');

        if(!empty($param['custom_price'])){
            if($param['custom_price'] < 500) Throw new Exception('自定义金额不能低于500！');
        }

        $addressInfo = [];
        $userAddress = '';
        if(!empty($param['address_id'])) {
            $addressServices = app()->make(UserAddressServices::class);
            if (!$addressInfo = $addressServices->getOne(['uid' => $uid, 'id' => $param['address_id'], 'is_del' => 0])) {
                throw new Exception('地址选择有误!');
            }
            $addressInfo = $addressInfo->toArray();
            $userAddress = $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['street'] . ' '.$addressInfo['address_location_name'].' ' . $addressInfo['unit_name'].' ' . $addressInfo['layer_name'] .' '. $addressInfo['detail'];
        }
        $orderService = app()->make(StoreOrderCreateServices::class);

        $user_info = User::where("uid", $uid)->find();
        $order_id = $orderService->getNewOrderId();

        try {
            Db::startTrans();
            //创建礼品卡订单
            $add = [
                'type' => SetupLimits::ORDER_TYPE,  //订单类型
                'order_id' => $order_id,  //订单id
                'uid' => $uid,
                'real_name' => $addressInfo['real_name'] ?? $user_info['real_name'],
                'unique' => md5(microtime()),
                'user_phone' => $addressInfo['phone'] ?? $user_info['phone'],
                'user_address' => $userAddress ?? $user_info['address'],
                'address_id' => $param['address_id'] ?? '',
                'activity_id' => $param['gift_card_id'],
                'total_num' => $num,
                'total_price' => $param['total_price'],
                'pay_price' => $param['pay_price'],
                'status' => 10,
                'unit_id' => $param['unit_id'] ?? "",
                'add_time' => time(),
            ];
            $res = StoreOrder::create($add);

            //添加用户礼品卡
            if($num > 1){
                $price = explode(",", $param["price_text"]);
                for($i = 1; $i <= $num; $i++){
                    $number = self::generateCardNumber();
                    $add_card_user = [
                        "uid" => $uid,
                        "gift_card_id" => $param['gift_card_id'],
                        "order_id" => $order_id,
                        "type" => 1,
                        "type_bak" => 1,
                        "create_time" => time(),
                        "number" => $number,
                        'address_id' => $param['address_id'] ?? '',
                        'price_text' => $price[$i+1] ?? 0,
                        "card_pwd" => mt_rand(100000, 999999),
                        "custom_price" => $param['custom_price'] ?? null,
                    ];
                    GiftCardUser::create($add_card_user);
                }
            }else {
                $number = self::generateCardNumber();
                $add_card_user = [
                    "uid" => $uid,
                    "gift_card_id" => $param['gift_card_id'],
                    "order_id" => $order_id,
                    "type" => 1,
                    "type_bak" => 1,
                    "create_time" => time(),
                    "number" => $number,
                    'address_id' => $param['address_id'] ?? '',
                    'price_text' => $param['total_price'],
                    "card_pwd" => mt_rand(100000, 999999),
                    "custom_price" => $param['custom_price'] ?? null,
                ];
                GiftCardUser::create($add_card_user);
            }
            SetupLimits::where("id", $param['gift_card_id'])->dec('stock_num', $num)->update();

            Db::commit();

        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }

        return ["order_id"=>$order_id, "card_number" => $number];
    }

    public static function generateCardNumber($len = 4)
    {
        $int_str = '';
        for($i=1; $i <= $len; $i++){
            if($i != 3){
                $str = mt_rand(1000, 9999) . " ";
                $int_str .= $str;
            }else{
                $str = '00'.mt_rand(10, 99) . " ";
                $int_str .= $str;
            }
        }
        $int_str = rtrim($int_str);
        return $int_str;
    }


    /**
     * 全部订单列表
     * @param int $uid
     * @param array $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftOrderList(int $uid, array $param)
    {
        $data["data"] = StoreOrder::field("id,type,order_id,uid,activity_id,FROM_UNIXTIME(add_time) as add_time,pay_time,status,paid,address_id,total_num,total_price,pay_price")
            ->with([
                'giftcard'=> function($query) {
                    $query->field ('*');
                },
                'carduser'=> function($query) {
                    $query->field ('*');
                },
            ])
            ->where("uid", $uid)
            //->where("status", '<>', self::ORDER_CANCEL_STATUS)
            ->where("is_system_del", 0)
            ->where("is_del", 0)
            ->where("type", SetupLimits::ORDER_TYPE)
            ->where(function ($query) use ($param){
                if(!empty($param['order_status'])) {
                    if($param['order_status'] == 22){  //待发货
                        $query->where("status", 0)->where('address_id','<>', '');
                    } else{
                        $query->where("status", $param['order_status']);
                    }
                }
                if(!empty($param['paid'])){
                    if($param['paid'] == 22){  //待付款
                        $query->where("paid", 0);
                    } else{
                        $query->where("paid", $param['paid']);
                    }
                }
            })
            ->page($param["page"], $param["limit"])
            ->select()
            ->each(function (&$item) {
                $item['pay_time'] = $item['pay_time'] ? date("Y-m-d H:i:s", $item['pay_time']) : $item['pay_time'];
            })
            ->toArray();

        $data["count"] = StoreOrder::field("id,type,order_id,uid,activity_id,FROM_UNIXTIME(add_time) as add_time,status,paid,total_num,total_price,pay_price")
            ->with([
                'giftcard'=> function($query) {
                    $query->field ('*');
                },
                'carduser'=> function($query) {
                    $query->field ('*');
                },
            ])
            ->where("uid", $uid)
            //->where("status", '<>', self::ORDER_CANCEL_STATUS)
            ->where("is_system_del", 0)
            ->where("is_del", 0)
            ->where("type", SetupLimits::ORDER_TYPE)
            ->where(function ($query) use ($param){
                if(!empty($param['order_status'])) {
                    if($param['order_status'] == 22){  //待发货
                        $query->where("status", 0)->where('address_id','<>', '');
                    } else{
                        $query->where("status", $param['order_status']);
                    }
                }
                if(!empty($param['paid'])){
                    if($param['paid'] == 22){  //待付款
                        $query->where("paid", 0);
                    } else{
                        $query->where("paid", $param['paid']);
                    }
                }
            })
            ->count();

        return $data;
    }


    /**
     * 取消/删除礼品卡订单
     * @param array $param
     * @return StoreOrder
     * @throws Exception
     */
    public static function cancelGiftOrder(array $param)
    {
        try {
            Db::startTrans();
            if($param["type"] == 1){
                //取消订单
                $res = StoreOrder::where("order_id", $param["order_id"])->update(["status" => self::ORDER_CANCEL_STATUS]);
                GiftCardUser::where("order_id", $param["order_id"])->update(["type" => self::ORDER_CANCEL_TYPE]);
            }
            elseif($param["type"] == 2)
            {
                //删除订单
                $res = StoreOrder::where("order_id", $param["order_id"])->update(["is_system_del" => 1]);
                GiftCardUser::where("order_id", $param["order_id"])->update(["delete_time" => time()]);
            }

            Db::commit();
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }
        return $res;
    }


    /**
     * 礼品卡后台 - 礼品卡管理列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftCardDataList($param = [])
    {
        $data["data"] = self::field ("*,FROM_UNIXTIME(create_time) as create_time")
            ->with([
                "catetag" => function ($query) {
                    $query->field("id,cate_tag_name");
                }
            ])
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("title",'like', '%'.$param["word"].'%');
            })
            ->order("id", "desc")
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data["count"] = self::field ("*")
            ->whereNull("delete_time")
            ->where(function ($query) use ($param){
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("title",'like', '%'.$param["word"].'%');
            })
            ->count();

        if(!empty($data["data"])){
            foreach($data["data"] as $key => &$val){
                $val["saled_num"] = self::getGiftSaledNum($val["id"]);
            }
        }
        return $data;
    }



    public static function getGiftSaledNum($id = '')
    {
        return StoreOrder::where(["type" =>31, "paid"=>1])->where("activity_id", $id)->sum('total_num') ?? 0;
    }


    /**
     * 礼品卡管理列表 - 添加
     * @param $param
     * @return int|string
     */
    public static function addGiftCard($param = [])
    {
        $add = [
            "tag_id"            => $param["tag_id"] ?? '',
            "title"             => $param["title"] ?? '',
            "price"             => $param["price"] ?? '',
            "price2"            => $param["price2"] ?? '',
            "img"               => $param["img"] ?? '',
            "theme"             => $param["theme"] ?? '',
            "detail_chart"      => $param["detail_chart"] ?? '',
            "content"           => $param["content"] ?? '',
            "unit"              => $param["unit"] ?? '',
            "stock_num"         => $param["stock_num"] ?? '',
            "original_price"    => $param["original_price"] ?? '',
            "subscript_price"   => $param["subscript_price"] ?? '',
            "bless"             => $param["bless"] ?? '',
            "freight"           => $param["freight"] ?? '',
            "notice"            => $param["notice"] ?? '',
            "is_custom"         => $param["is_custom"] ?? '',
            "make_start_price"  => $param["make_start_price"] ?? '',
            "moral"             => $param["moral"] ?? '',
            "ground"            => $param["ground"] ?? '',
            "create_time"       => time(),
        ];
        return self::insert($add);
    }




    /**
     * 礼品卡管理列表 - 编辑
     * @param $param
     * @return RecruitLanguage
     */
    public static function updateGiftCard($param = [])
    {
        $update["update_time"] = time();  //更新时间
        if(!empty($param["tag_id"]))                $update["tag_id"] = $param["tag_id"];  //分类标签id
        if(!empty($param["title"]))                 $update["title"] = $param["title"]; //标题
        if(!empty($param["price"]))                 $update["price"] = $param["price"]; //价格
        if(!empty($param["price2"]))                $update["price2"] = $param["price2"]; //价格2
        if(!empty($param["img"]))                   $update["img"] = $param["img"]; //图片
        if(!empty($param["theme"]))                 $update["theme"] = $param["theme"]; //主题
        if(!empty($param["detail_chart"]))          $update["detail_chart"] = $param["detail_chart"]; //详情图
        if(!empty($param["content"]))               $update["content"] = $param["content"]; //图文详情
        if(!empty($param["unit"]))                  $update["unit"] = $param["unit"]; //单位
        if(!empty($param["stock_num"]))             $update["stock_num"] = $param["stock_num"]; //库存
        if(!empty($param["original_price"]))        $update["original_price"] = $param["original_price"]; //原价
        if(!empty($param["subscript_price"]))       $update["subscript_price"] = $param["subscript_price"]; //折扣金额
        if(!empty($param["bless"]))                 $update["bless"] = $param["bless"]; //祝福语
        if(!empty($param["freight"]))               $update["freight"] = $param["freight"]; //运费
        if(!empty($param["make_start_price"]))      $update["make_start_price"] = $param["make_start_price"]; //制作实体卡起始金额
        if(!empty($param["ground"]))                $update["ground"] = $param["ground"]; //祝福语背景图
        if(!empty($param["notice"]))                $update["notice"] = $param["notice"]; //购买须知
        if(!empty($param["is_custom"]))             $update["is_custom"] = $param["is_custom"]; //是否可以自定义金额 1是 2否
        if(!empty($param["moral"]))                 $update["moral"] = $param["moral"]; //寓意

        return self::where("id", $param["id"])->update($update);
    }


    /**
     * 礼品卡管理列表 - 启用禁用
     * @param $param
     * @return string
     */
    public static function enableGiftCard($param = [])
    {
        //获取用户发送的id，根据状态修改当前banner的启用禁用状态
        $status = self::where("id", $param['id'])->value("status");
        $msg = '';
        if($status == 1){   //1启用 2禁用
            $enable = 2;
            $msg = "禁用成功";
        }else{
            $enable = 1;
            $msg = "启用成功";
        }
        self::where("id", $param['id'])->update(['status' => $enable]);
        return $msg;
    }



}